import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from '@/router/routes'

import Cookie from 'js-cookie'


Vue.use(VueRouter)




/* 重写push和replace方法 */
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve, reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}


VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve, reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

let router = new VueRouter({
    routes,
    scrollBehavior() {
        return { y: 0 }
    },
})


/* 前置路由首位 */
router.beforeEach((to, from, next) => {
    /* 判断token是否存在 */
    const token = Cookie.get('token')
    if (!token && to.name != 'logoin') {
        next({ name: 'logoin' })
    } else if (token && to.name == 'logoin') {
        next({ name: 'home' })
    } else {
        next()
    }
})




export default router




